package org.visionlibrary.image.filters.resampling;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class NearestNeighbour extends AbstractFilter {
	protected int newWidth = 1024;
	protected int newHeight = 1024;

	public NearestNeighbour() {
		this(128,128);
	}
	
	public NearestNeighbour(int newWidth, int newHeight) {
		this.newWidth = newWidth;
		this.newHeight = newHeight;
	}

	public TiledImage applyFilter(TiledImage src, TiledImage dest)
			throws IllegalArgumentException {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (dest != null)
			throw new IllegalArgumentException(
					"this only works with construction:\ndest = filter.applyFilter( src, null );");

		dest = (new ImageFactory()).createCompatibleImage(src, newWidth, newHeight);

		float ratiox = src.getWidth() * 1.0f / newWidth * 1.0f;
		float ratioy = src.getHeight() * 1.0f / newHeight * 1.0f;

		int maxX = dest.getWidth();
		int maxY = dest.getHeight();
		for (int ch = 0; ch < src.getNumBands(); ch++)
			for (int x = 0; x < maxX - 1; x++)
				for (int y = 0; y < maxY - 1; y++) {
					int i = (int) (x * ratiox);
					int j = (int) (y * ratioy);
					int val = src.getSample(i, j, ch);
					dest.setSample(x, y, ch, val);
				}

		return dest;
	}

	public int getNewHeight() {
		return newHeight;
	}

	public int getNewWidth() {
		return newWidth;
	}

	public void setNewHeight(int newHeight) {
		this.newHeight = newHeight;
	}

	public void setNewWidth(int newWidth) {
		this.newWidth = newWidth;
	}
}
